/*
 * Copyright 2013-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shen.demo.demos.web;

import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.MapSearcher;
import cn.zhxu.bs.SearchResult;
import cn.zhxu.bs.util.MapUtils;
import com.shen.demo.demos.web.domain.Users;
import com.shen.demo.demos.web.tool.StrReverseTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
 */
@Controller
public class BasicController {
    private static final Logger log = LoggerFactory.getLogger(BasicController.class);
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 注入 Map 检索器，它检索出来的数据以 Map 对象呈现
     */
    @Autowired
    private MapSearcher mapSearcher;
    /**
     * 注入 Bean 检索器，它检索出来的数据以 泛型 对象呈现
     */
    @Autowired
    private BeanSearcher beanSearcher;
    @Autowired
    private StrReverseTool strTool;



    // http://127.0.0.1:8080/hello?name=lisi
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(@RequestParam(name = "name", defaultValue = "unknown user") String name) {
        return "Hello " + name;
    }

    // http://127.0.0.1:8080/user
    @RequestMapping("/user")
    @ResponseBody
    public User user() {
        User user = new User();
        user.setName("theonefx");
        user.setAge(666);
        return user;
    }

    // http://127.0.0.1:8080/save_user?name=newName&age=11
    @RequestMapping("/save_user")
    @ResponseBody
    public String saveUser(User u) {
        return "user will save: name=" + u.getName() + ", age=" + u.getAge();
    }

    // http://127.0.0.1:8080/html
    @RequestMapping("/html")
    public String html(){
        return "index.html";
    }

    @ModelAttribute
    public void parseUser(@RequestParam(name = "name", defaultValue = "unknown user") String name
            , @RequestParam(name = "age", defaultValue = "12") Integer age, User user) {
        user.setName("zhangsan");
        user.setAge(18);
    }
    @RequestMapping("/setStringRedisTemplate")
    @ResponseBody
    public Object setStringRedisTemplate( ) {
//        redisTemplate.opsForValue().set("hello", "world");
        return redisTemplate.opsForValue().get("hello");

    }
    @RequestMapping("/list")
    @ResponseBody
    public List<String> listTest() {
        ListOperations<String, String> listOperations = redisTemplate.opsForList();
        listOperations.leftPush("list", "hello");
        listOperations.leftPush("list", "world");
        listOperations.leftPush("list", "java");
        List<String> list = listOperations.range("list", 0, 2);   // 取 key 值为 list 的索引0到索引2的list
        return list;
    }
    @RequestMapping("/set")
    @ResponseBody
    public Set<String> setTest() {
        SetOperations<String, String> setOperations = redisTemplate.opsForSet();
        setOperations.add("set", "hello");
        setOperations.add("set", "world");
        setOperations.add("set", "world");
        setOperations.add("set", "java");
        Set<String> set = setOperations.members("set");   // 取 set
        return set;
    }
    @RequestMapping("/zset")
    @ResponseBody
    public Set<String> zsetTest() {
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        zSetOperations.add("zset", "java", 1);
        zSetOperations.add("zset", "hello", 3);
        zSetOperations.add("zset", "world", 2);
        Set<String> set = zSetOperations.range("zset", 0, 2);
        return set;
    }
    @RequestMapping("/hash")
    @ResponseBody
    public String hashTest() {
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        hashOperations.put("key", "hashkey1", "hello11");
        hashOperations.put("key", "hashkey2", "world1");
        hashOperations.put("key", "hashkey3", "java1");
        return hashOperations.get("key", "hashkey2");
    }

    /**
     * bean Searcher 高级查询
     * @param request
     * @return
     */
    @GetMapping("/index/user")
    @ResponseBody
    public SearchResult<Map<String, Object>> index(HttpServletRequest request) {
        // 一行代码，实现一个用户检索接口（MapUtils.flat 只是收集前端的请求参数）
        return mapSearcher.search(Users.class, MapUtils.flat(request.getParameterMap()));
    }
    @RequestMapping("/str")
    @ResponseBody
    public String str(@RequestParam(name = "key", defaultValue = "unknown key") String key) {
        final HashMap<Object, Object> hashMap =  new HashMap<>();
        hashMap.put("hash1", " hello11");
        hashMap.put("hash2","world ");
        hashMap.put("hash3","j a v a");
        log.info("{}的字符数量为：{}",key, hashMap.get(key).toString().length());
        String reverse = strTool.reverse(hashMap.get(key).toString());
        log.info("{}的字符解析后长度为：{}",key, reverse.length());
        return reverse;

    }

}
